package com.syni.mdd.yhd.common.all.utils;

import lombok.extern.log4j.Log4j2;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @className PictureUtil
 * @description 图片处理
 * @Author cfx
 * @DATE 2019/10/8 9:25
 * @VERSION 1.0
 **/
@Component
@Log4j2
public class PictureUtil {
    @Value("${app.headImg.tmpUrl:D:/setting/img}")
    private static String headImgTmpLocation;



    public static void main(String[] args) {
        String url = "D:/setting/img/a.pdf";
        pdf2png(url,"jpg");
    }

    /**
     * 转换全部的pdf
     * @param filePath 文件地址
     * @param type 图片类型
     */
    public static List<String> pdf2png(String filePath,String type) {
        // 将pdf装图片 并且自定义图片得格式大小
        List<String> imgList = new ArrayList<>();
        File file = new File(filePath);
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                //获取pdf
                String[] preFile = filePath.split("\\.");
                String saveUrl = String.format("%s_%s.%s",preFile[0],i+1,type);
                imgList.add(saveUrl);
                ImageIO.write(image, type, new File(saveUrl));
            }
            return imgList;
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }


}
